package com.cy.demo1.controller;

import com.cy.demo1.entity.Data;
import com.cy.demo1.service.IDataService;
import com.cy.demo1.util.JsonResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
public class DataController extends BaseController{

    @Resource
    private IDataService dataService;

    @RequestMapping("showData")
    public JsonResult<Data[]> showData() {
        Integer number = dataService.countProject();
        Data data[] = dataService.showData();
        //return new JsonResult<Data[]>(OK, number, data);
        return new JsonResult<Data[]>(OK, data);
    }

    @PostMapping("uploadData")
//    public JsonResult<Void> uploadData(String projectName, String dataSet) {
//        Data data = new Data();
//        data.setProjectName(projectName);
//        data.setProjectData(dataSet);
//        dataService.uploadData(data);
//
//        return new JsonResult<>(OK);
//    }
    public JsonResult<Void> uploadData(@RequestParam MultipartFile file) throws Exception{
//                System.out.println( file.getInputStream());
        String filename=file.getOriginalFilename();
//        String str[] = filename.split(".");
//        for(int i=0;i < str.length;i++) {
//            System.out.println(str[i]);
//        }
        System.out.println(filename);
        String projectName = filename.substring(0,filename.lastIndexOf("."));
        System.out.println(projectName);
        InputStream ins = file.getInputStream();
        byte[] buffer = new byte[ins.available()];
        ins.read(buffer);
        File targetFile = new File("src/main/resources/"+filename);
        OutputStream outStream = new FileOutputStream(targetFile);
        outStream.write(buffer);

        Data data = new Data();
        data.setProjectName(projectName);
        data.setProjectData("src/main/resources/"+filename);
        dataService.uploadData(data);

        return new JsonResult<>(OK);
    }

}
